<template>
    <div class="page">
        <div class="breadcrumb-box">
            <el-breadcrumb separator-class="el-icon-arrow-right">
                <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
                <el-breadcrumb-item>购物车</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="line">
            <img :src="$global.Image.icon_goods_line" />
        </div>
        <div class="container">
            <div class="cart-top td-fss">
                <label class="td-fbc btn-cp" @click="allChecked">
                    <img class="icon-checked" v-if="isAllSelect && cartCount > 0" :src="$global.Image.icon_checked" />
                    <img class="icon-checked" v-else :src="$global.Image.icon_checked_grey" />
                    <span>全选</span>
                </label>
                <div class="cart-td1">商品</div>
                <div class="cart-td2">单价</div>
                <div class="cart-td3">数量</div>
                <div class="cart-td2">小计</div>
                <div class="cart-td2">操作</div>
            </div>
            <ul class="cart-list">
                <li class="td-fss" v-for="(item, index) in cartList.valid" :key="index">
                    <div class="cart-td1 td-fsc">
                        <img class="icon-checked" :src="
                item.checked
                  ? $global.Image.icon_checked
                  : $global.Image.icon_checked_grey
              " @click="switchSelect(index)" />
                        <img class="goods-img" :src="
                item.productInfo.attrInfo
                  ? item.productInfo.attrInfo.image
                  : item.productInfo.image
              " @click="$router.push({ path: '/detail/' + item.product_id})" />
                        <div class="td-f1 goods-info" @click="$router.push({ path: '/detail/' + item.product_id})">
                            <div class="name">{{ item.productInfo.store_name }}</div>
                            <div class="price">规格：{{ item.productInfo.attrInfo.suk }}</div>
                        </div>
                    </div>
                    <div class="cart-td2 td-fbc" v-if="item.truePrice">
                        <div class="goods-attr">¥{{ item.truePrice }}</div>
                        <!-- <span class="edit-btn">修改</span> -->
                    </div>
                    <div class="cart-td2 td-fbc" v-else>
                        <div class="goods-attr">无</div>
                    </div>
                    <div class="cart-td3 td-fcc">
                        <el-input-number style="width: 105px;" v-model="item.cart_num" size="mini" :min="1" :max="stock" label="数量" @change="_changeCartNum(arguments, index)"></el-input-number>
                    </div>
                    <div class="cart-td2 td-fcc">
                        <span class="amount">¥{{ (item.truePrice * item.cart_num).toFixed(2) }}</span>
                    </div>
                    <div class="cart-td2 td-fcc">
                        <div class="choose">
                            <div class="del" @click="delgoods(item.id)">删除</div>
                            <div class="collect" @click="collectAll(item.product_id,item.type)" v-if="item.productInfo.collect == 0">收藏</div>
                            <div class="collect" @click="getCollectDels(item.product_id,item.type)" v-else>已收藏</div>
                        </div>
                    </div>
                </li>
                <div class="nodata" v-if="cartList.valid.length == 0">
                    <img :src="$global.Image.noGood" />
                    <div class="td-fcc to-shop">
                        <el-button class="btn-r" @click="$router.replace('/')">去购物</el-button>
                    </div>
                </div>
            </ul>
            <v-recommend :type="'hot'" @callback="recommendCallback"></v-recommend>
        </div>
        <div class="cart-bottom">
            <div class="container td-fbc">
                <div class="td-fbc left" style="flex:1">
                    <label class="td-fbc btn-cp" @click="exportGood">
                        导出
                    </label>
                    <!-- <span class="span-btn btn-cp" @click="delgoods">删除选中产品</span>
                    <span class="span-btn btn-cp" @click="collectAll">收藏选中产品</span> -->
                    <div class="span-btn choose-good">已选择<b>{{ cartCount }}</b>件商品</div>
                </div>
                <div class="td-fec">
                    <div class="total-box td-fae td-fc">
                        <div>
                            需要支付：<span>￥{{ countmoney }}</span>
                        </div>
                        <!-- <div class="discount">已优惠：￥100.00</div> -->
                    </div>
                    <Btn :loading="true" class="btn-r" @confirmEvent="placeOrder">立即支付</Btn>
                </div>
            </div>
        </div>
        <div v-show="showDialog">
            <div class="add-address-show">
                <div class="title">
                    <div>清单导出</div>
                    <img :src="$global.Image.icon_close" @click="_cancelDialog" />
                </div>
                <div class="add-input">
                    <div class="scroll">
                        <div class="goods-itm" v-for="(item,index) in selectGood" :key="index">
                            <img :src="item.productInfo.attrInfo ? item.productInfo.attrInfo.image : item.productInfo.image" alt="" class="goods-img">
                            <div class="goods-right">
                                <div class="goods-tit">{{item.productInfo.store_name}}</div>
                                <div class="goods-choies">
                                    <span class="span1">规格：{{ item.productInfo.attrInfo.suk }}</span>
                                    <span class="span2">x {{item.cart_num}}</span>
                                </div>
                                <div class="goods-price" v-if="item.truePrice">¥ {{ item.truePrice }}</div>
                            </div>
                        </div>
                    </div>
                    <div class="email">
                        <div class="email-tit"><span>*</span>收件邮箱</div>
                        <el-input v-model="email" placeholder="请输入收件邮箱"></el-input>
                    </div>
                    <div class="history" v-if="historyEmail.length">
                        <div class="history-list">
                            <div class="" v-for="(item,index) in historyEmail" :key="index" @click="historyClick(item)">
                                <img @click.stop="delHistory(index)" src="../assets/second_icon/close_icon.png" alt="">
                                {{item}}
                            </div>
                        </div>
                    </div>
                    <div class="choose-type">
                        <div class="cancel" @click="_cancelDialog">取消</div>
                        <div class="confirm" @click="_confirmDialog">确认</div>
                    </div>
                </div>
            </div>
            <div class="dialog-shade"></div>
        </div>
    </div>
</template>

<script>
import Recommend from "@components/Recommend";
import {
    getCartList,
    postCartDel,
    changeCartNum,
    getCartCount,
} from "@api/store";
import { postCollectAll, exportProduct, getCollectDel } from "@api/user";
import { mul, add } from "@utils/bc";
import cookie from "@utils/store/cookie";
import debounce from "lodash.debounce";

const CHECKED_IDS = "cart_checked";

export default {
    components: {
        "v-recommend": Recommend,
    },
    data() {
        return {
            showDialog: false,
            cartList: { invalid: [], valid: [] },
            isAllSelect: false,
            cartCount: 0,
            countmoney: 0,
            goodsHidden: true,
            footerswitch: false,
            count: 0,
            historyEmail: [],
            selectGood: [],
            checkedIds: [],
            email: "",
            loaded: false,
            index_num: 0,
        };
    },
    mounted() {
        let that = this;
        that.carnum();
        that.countMoney();
        that.getCartList();
        that.gainCount();
        if (localStorage.getItem("historyEmail")) {
            this.historyEmail = JSON.parse(
                localStorage.getItem("historyEmail")
            );
        }
    },
    methods: {
        delHistory(index) {
            this.historyEmail.splice(index, 1);
            let arr = this.historyEmail;

            localStorage.setItem("historyEmail", JSON.stringify(arr));
            console.log(this.historyEmail, arr);
        },
        historyClick(e) {
            this.email = e;
        },
        _confirmDialog() {
            let selectGood = this.selectGood;
            let id = [];
            selectGood.map((item, index) => {
                id.push(item.id);
            });
            let email = this.email;
            let data = {
                email: email,
                type: 0,
                id: id.join(","),
            };
            if (!data.email) {
                return this.$dialog.toast({ mes: "请输入邮箱" });
            }
            exportProduct(data)
                .then((res) => {
                    if (res.status == 200) {
                        let arr =
                            JSON.parse(localStorage.getItem("historyEmail")) ||
                            [];

                        arr = arr.concat(email);
                        localStorage.setItem(
                            "historyEmail",
                            JSON.stringify(arr)
                        );
                        this.historyEmail = arr;
                        this.$dialog.toast({ mes: "提交成功" });

                        setTimeout(() => {
                            this.showDialog = false;
                        }, 1000);
                        return;
                    }
                    this.$dialog.toast({ mes: res.msg });
                })
                .catch((err) => {
                    console.log(err);
                    this.$dialog.toast({ mes: res.msg });
                });
        },
        exportGood() {
            let selectGood = this.selectGood;
            selectGood = [];
            if (this.checkedIds.length == 0) {
                return;
            }
            this.checkedIds.map((item, index) => {
                this.cartList.valid.map((items, index) => {
                    if (item == items.id) {
                        console.log(items);
                        selectGood.push(items);
                    }
                });
            });
            this.selectGood = selectGood;
            this.showDialog = true;
        },
        _cancelDialog() {
            this.showDialog = false;
        },
        getCartList() {
            let that = this;
            getCartList().then((res) => {
                that.cartList = res.data;
                let checkedIds = cookie.get(CHECKED_IDS) || [];
                if (!Array.isArray(checkedIds)) checkedIds = [];
                this.cartList.valid.forEach((cart) => {
                    if (checkedIds.length) {
                        if (checkedIds.indexOf(cart.id) !== -1)
                            cart.checked = true;
                        else cart.checked = false;
                    } else {
                        cart.checked = true;
                        that.checkedIds.push(cart.id);
                    }
                });
                if (checkedIds.length) {
                    that.checkedIds = checkedIds;
                }
                that.isAllSelect =
                    that.checkedIds.length === this.cartList.valid.length;
                that.carnum();
                that.countMoney();
                this.loaded = true;
            });
        },
        //删除商品；
        delgoods(id) {
            let that = this,
                ids = [],
                valid = [],
                list = that.cartList.valid;
            ids.push(id);
            postCartDel(ids).then(function () {
                that.getCartList();
            });
        },
        //获取数量
        gainCount() {
            let that = this;
            getCartCount().then((res) => {
                that.count = res.data.count;
                this.$store.dispatch("CART_NUM");
            });
        },
        //清除失效产品；
        delInvalidGoods() {
            let that = this,
                id = [],
                list = that.cartList.invalid;
            list.forEach(function (val) {
                id.push(val.id);
            });
            postCartDel(id).then(function () {
                list.splice(0, list.length);
                that.gainCount();
            });
        },
        getCollectDels(product_id, type) {
            let that = this,
                data = { id: [], category: "" };
            data.id.push(product_id);
            data.category = type;
            getCollectDel(product_id, data.category)
                .then((res) => {
                    that.$dialog.toast({ mes: "取消成功!" });
                    setTimeout(() => {
                        that.getCartList();
                    }, 1000);
                })
                .catch((err) => {});
        },
        //批量收藏;
        collectAll(product_id, type) {
            let that = this,
                data = { id: [], category: "" };
            data.id.push(product_id);
            data.category = type;

            postCollectAll(data).then(function () {
                that.$dialog.toast({ mes: "收藏成功!" });
                setTimeout(() => {
                    that.getCartList();
                }, 1000);
            });
        },
        //立即下单；
        placeOrder(done) {
            let that = this,
                list = that.cartList.valid,
                id = [];
            list.forEach(function (val) {
                if (val.checked === true) {
                    id.push(val.id);
                }
            });
            if (id.length === 0) {
                that.$dialog.toast({ mes: "请选择产品" });
                done();
                return;
            }
            this.$router.push({ path: "/orderConfirm/" + id });
        },
        manage() {
            let that = this;
            that.footerswitch = !that.footerswitch;
        },
        goodsOpen() {
            let that = this;
            that.goodsHidden = !that.goodsHidden;
        },
        //单选
        switchSelect(index) {
            let that = this,
                cart = that.cartList.valid[index],
                i = this.checkedIds.indexOf(cart.id);
            cart.checked = !cart.checked;
            if (i !== -1) this.checkedIds.splice(i, 1);
            if (cart.checked) {
                this.checkedIds.push(cart.id);
            }
            let len = that.cartList.valid.length;
            let selectnum = [];
            for (let i = 0; i < len; i++) {
                if (that.cartList.valid[i].checked === true) {
                    selectnum.push(true);
                }
            }
            that.isAllSelect = selectnum.length === len;
            that.$set(that, "cartList", that.cartList);
            that.$set(that, "isAllSelect", that.isAllSelect);
            cookie.set(CHECKED_IDS, that.checkedIds);
            that.carnum();
            that.countMoney();
        },
        // 数量变化
        _changeCartNum(arg, index) {
            let that = this;
            let list = that.cartList.valid[index];
            list.cart_num = arg[0];
            if (list.attrInfo) {
                if (list.cart_num >= list.attrInfo.stock) {
                    that.$set(list, "cart_num", list.attrInfo.stock);
                }
            } else {
                if (list.cart_num >= list.stock) {
                    that.$set(list, "cart_num", list.stock);
                }
            }
            that.carnum();
            that.countMoney();
            that.syncCartNum(list);
            this.carnum();
            this.countMoney();
        },
        syncCartNum(cart) {
            if (!cart.sync)
                cart.sync = debounce(() => {
                    changeCartNum(
                        cart.id,
                        Math.max(cart.cart_num, 1) || 1
                    ).then(() => {
                        this.$store.dispatch("CART_NUM");
                    });
                }, 500);
            cart.sync();
        },
        //全选
        allChecked() {
            let that = this;
            let selectAllStatus = that.isAllSelect;
            selectAllStatus = !selectAllStatus;
            let checkedIds = [];
            // for (let i = 0; i < array.length; i++) {
            //   array[i].checked = selectAllStatus;
            //   checked.push()
            // }
            that.cartList.valid.forEach((cart) => {
                cart.checked = selectAllStatus;
                if (selectAllStatus) checkedIds.push(cart.id);
            });
            that.$set(that, "cartList", that.cartList);
            that.$set(that, "isAllSelect", selectAllStatus);
            this.checkedIds = checkedIds;
            cookie.set(CHECKED_IDS, checkedIds);
            that.carnum();
            that.countMoney();
        },
        //数量
        carnum() {
            let that = this;
            var carnum = 0;
            var array = that.cartList.valid;
            for (let i = 0; i < array.length; i++) {
                if (array[i].checked === true) {
                    if (array[i].cart_num)
                        carnum += parseInt(array[i].cart_num);
                }
            }
            this.cartCount = carnum;
        },
        //总共价钱；
        countMoney() {
            let that = this;
            let carmoney = 0;
            let array = that.cartList.valid;
            for (let i = 0; i < array.length; i++) {
                if (array[i].checked === true) {
                    carmoney = add(
                        carmoney,
                        mul(array[i].cart_num, array[i].truePrice)
                    );
                }
            }
            that.countmoney = carmoney;
        },
        recommendCallback(res) {
            if (res == "reload") {
                this.carnum();
                this.countMoney();
                this.getCartList();
                this.gainCount();
            }
        },
    },
};
</script>

<style scoped  rel="stylesheet/scss" lang="scss" scoped>
.position {
    margin: 40px 0 24px;
}
.line {
    width: 1200px;
    margin: 0 auto 30px;
    img {
        display: block;
        width: 100%;
    }
}
.cart-top {
    height: 46px;
    padding: 0 20px;
    background: #fbf7f7;
    border: 1px solid #eaa090;
    display: flex;
    align-items: center;
    .btn-cp:hover {
        color: #da213d;
        span {
            color: #da213d;
        }
    }
    span {
        font-size: 14px;
        font-weight: bold;
        color: #999999;
    }
    .icon-checked {
        height: 20px;
        width: 20px;
        object-fit: contain;
        margin-right: 10px;
    }
    div {
        height: 46px;
        font-size: 14px;
        font-weight: 700;
        color: #999999;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    .cart-td1 {
        flex: 1;
    }
    .cart-td2 {
        width: 160px;
    }
    .cart-td3 {
        width: 260px;
    }
    .cart-td4 {
        width: 100px;
    }
}
.history {
    width: 400px;
    margin: 20px auto 20px;
    .history-list {
        display: flex;
        flex-wrap: wrap;
        div {
            border-radius: 10px;
            padding: 5px;
            box-sizing: border-box;
            font-size: 16px;
            line-height: 16px;
            color: #999;
            background: #f8f8f8;
            margin: 0px 5px 5px;
            cursor: pointer;
            position: relative;
            img {
                position: absolute;
                right: -10px;
                top: -10px;
                width: 20px;
                height: 20px;
            }
        }
    }
}
.cart-list {
    margin-top: 24px;
    li {
        border: solid #dbdbdb 1px;
        padding: 0 20px;
        height: 150px;
        display: flex;
        align-items: center;
        margin-bottom: 20px;
        .cart-td1 {
            flex: 1;
        }
        .cart-td2 {
            width: 160px;
            div {
                text-align: center;
                width: 100%;
                font-size: 14px;
                color: #333333;
                line-height: 19px;
                font-weight: bold;
            }
            .choose {
                position: relative;
                &::before {
                    content: "";
                    top: 0;
                    bottom: 0;
                    margin: auto 0;
                    position: absolute;
                    left: 0;
                    width: 1px;
                    height: 60px;
                    opacity: 0.2;
                    background: #414141;
                }
                .del {
                    font-size: 13px;
                    color: #da213d;
                    line-height: 18px;
                }
                .collect {
                    margin-top: 10px;
                    font-size: 13px;
                    color: #3ca9d7;
                    line-height: 18px;
                }
            }
        }
        .cart-td3 {
            width: 260px;
        }
        .cart-td4 {
            width: 100px;
        }
        .icon-checked {
            height: 20px;
            width: 20px;
            object-fit: contain;
        }
        .goods-img {
            display: block;
            width: 100px;
            height: 100px;
            object-fit: cover;
            margin-left: 20px;
        }
        .goods-info {
            height: 100px;
            margin-left: 20px;
            padding-right: 30px;
        }
        .name {
            padding-top: 10px;
            cursor: pointer;
            font-size: 16px;
            color: #333333;
            line-height: 21px;
        }
        .price {
            font-size: 16px;
            color: #999999;
            margin-top: 10px;
        }
        .goods-attr {
            font-size: 14px;
            color: #333;
        }
        .edit-btn {
            width: 48px;
            height: 24px;
            border-radius: 2px;
            font-size: 14px;
            background-color: #da213d;
            color: #014a97;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .amount {
            font-size: 16px;
            font-weight: 700;
            color: #da213d;
        }
    }
}

.cart-bottom {
    background-color: #fff;
    position: fixed;
    z-index: 99;
    bottom: 0;
    left: 0;
    width: 100%;
    box-shadow: 0 -5px 10px rgba($color: #000000, $alpha: 0.2);
    .container {
        height: 80px;
    }
    .icon-checked {
        height: 20px;
        width: 20px;
        object-fit: contain;
        margin-right: 10px;
    }
    .left {
        .btn-cp {
            cursor: pointer;
            width: 108px;
            display: block;
            font-size: 13px;
            text-align: center;
            color: #ffffff;
            line-height: 34px;
            height: 34px;
            background: linear-gradient(143deg, #da213d 23%, #da213d 90%);
            border-radius: 5px;
        }

        .btn-cp:hover {
            // color: #da213d;
            span {
                color: #da213d;
            }
        }
        span {
            font-size: 16px;
            color: #333;
        }
        .choose-good {
            display: flex;
            justify-content: flex-end;
            align-items: center;
            flex: 1;
            margin-right: 68px;
        }
        .span-btn {
            color: #666;
            padding-left: 40px;
            b {
                font-size: 18px;
                padding: 0 4px;
            }
        }
    }
    .total-box {
        font-size: 16px;
        color: #333;
        margin-right: 70px;
        height: 60px;
        span {
            font-size: 24px;
            font-weight: 600;
            color: #da213d;
        }
        .discount {
            font-size: 14px;
            color: #999;
        }
    }
    .btn-r {
        height: 80px;
        width: 200px;
        font-size: 21px;
        font-weight: 700;
        letter-spacing: 2px;
        color: #ffffff !important;
    }
}
.to-shop {
    margin-top: 40px;
    button {
        width: 160px;
    }
}
.dialog-shade {
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    z-index: 100;
    background-color: rgba($color: #000000, $alpha: 0.4);
}
.add-address-show {
    position: fixed;
    left: 50%;
    top: 50%;
    width: 700px;
    transform: translate(-50%, -50%);
    border-radius: 4px;
    background-color: rgba(255, 255, 255, 1);
    box-shadow: 0 0 15px 4px rgba(0, 0, 0, 0.2);
    z-index: 101;
    .title {
        display: flex;
        width: 100%;
        height: 67px;
        align-items: center;
        background: #fbf0f0;
        justify-content: center;
        > div:nth-of-type(1) {
            font-size: 21px;
            font-weight: bold;
            color: #da213d;
        }
        img {
            display: block;
            width: 20px;
            height: 20px;
            font-size: 30px;
            color: #999999;
            position: absolute;
            right: 32px;
            cursor: pointer;
        }
    }
    .add-input {
        display: flex;
        justify-content: center;
        flex-direction: column;
        align-items: center;
        padding: 20px 0 40px;
        .scroll {
            height: 310px;
            width: 100%;
            overflow-y: scroll;
            &::-webkit-scrollbar {
                width: 0;
                height: 0;
                display: none;
            }
            .goods-itm {
                margin: 0 auto;
                width: 550px;
                height: 150px;
                border: 1px solid #eaa090;
                margin-bottom: 10px;
                display: flex;
                align-items: center;
                padding: 0 20px;
                box-sizing: border-box;
                .goods-img {
                    width: 126px;
                    height: 126px;
                }
                .goods-right {
                    margin-left: 20px;
                    .goods-tit {
                        font-size: 20px;
                        font-weight: bold;
                        text-align: justify;
                        color: #333333;
                        line-height: 26px;
                        text-overflow: -o-ellipsis-lastline;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        display: -webkit-box;
                        -webkit-line-clamp: 2;
                        -webkit-box-orient: vertical;
                    }
                    .goods-choies {
                        font-size: 14px;
                        color: #999999;
                        margin-top: 14px;
                        .span1 {
                        }
                        .span2 {
                            margin-left: 60px;
                        }
                    }
                    .goods-price {
                        margin-top: 10px;
                        font-size: 20px;
                        font-weight: bold;
                        color: #da213d;
                    }
                }
            }
        }
    }
    .rule-form {
        width: 460px;
        button {
            width: 140px;
        }
    }
}
.email {
    display: flex;
    margin-top: 20px;
    .email-tit {
        font-size: 15px;
        width: 100px;
        line-height: 40px;
        span {
            color: #da213d;
            font-size: 15px;
        }
    }
    .el-input {
        width: 400px;
    }
}
.choose-type {
    display: flex;
    justify-content: space-between;
    margin-top: 20px;
    width: 100%;
    padding: 0 70px;
    box-sizing: border-box;
    .cancel {
        width: 242px;
        height: 46px;
        border: 1px solid #da213d;
        border-radius: 5px;
        font-size: 16px;
        text-align: center;
        color: #da213d;
        line-height: 46px;
        cursor: pointer;
    }
    .confirm {
        width: 240px;
        height: 44px;
        background: #da213d;
        border-radius: 5px;
        font-size: 16px;
        text-align: center;
        color: #ffffff;
        line-height: 44px;
        cursor: pointer;
    }
}
</style>
